#include <libemb/BaseType.h>
#include <libemb/Tracer.h>
#include <libemb/ArgUtil.h>
#include <libemb/FSMachine.h>
#include <libemb/Thread.h>

using namespace libemb;
enum TestState{
	STATE_IDLE=0,
	STATE_START,
	STATE_STOP
};
class StateIdle:public FSHandler{
DECL_CLASSNAME(StateIdle)
public:
	int handleState()
	{
		if (m_circles--<0)
		{
			return -1;
		}
		TRACE_DBG_CLASS("enter IDLE state...");
		Thread::msleep(2000);
		TRACE_DBG_CLASS("exit IDLE state...");
		return STATE_START;
	}
private:
	int m_circles{2};
};

class StateStart:public FSHandler{
DECL_CLASSNAME(StateStart)
public:
	int handleState()
	{
		TRACE_DBG_CLASS("enter START state...");
		Thread::msleep(2000);
		TRACE_DBG_CLASS("exit START state...");
		return STATE_STOP;
	}
};

class StateStop:public FSHandler{
DECL_CLASSNAME(StateStop)
public:
	int handleState()
	{
		TRACE_DBG_CLASS("enter STOP state...");
		Thread::msleep(2000);
		TRACE_DBG_CLASS("exit STOP state...");
		return STATE_IDLE;
	}
};

class StateListener:public FSListener{
DECL_CLASSNAME(StateListener)
public:
	void onStateChanged(int stateID)
	{
		TRACE_DBG_CLASS("Aha! I get state changed: %d",stateID);
	}
};

void testFSMachine(void)
{
    TRACE_INFO("FSMachine test start >>>>>>");
	FSMachine machine;
	StateIdle idle;
	StateStart start;
	StateStop stop;
	StateListener listener;
	machine.registerState(STATE_IDLE,idle);
	machine.registerState(STATE_START,start);
	machine.registerState(STATE_STOP,stop);
	machine.registerListener(listener);
	machine.startup(STATE_IDLE);
	while(1)
	{
		InputReader reader;
		reader.waitInput();
        if (reader.isString("q") || reader.isString("quit")) 
        {
			machine.quit();
            break;
        }
	}
    TRACE_INFO("FSMachine test finished <<<<<<");
}
